package com.skzh.history.utils;

import com.skzh.flightplans.domain.Waypoints;
import com.skzh.history.domain.TaskHistory;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class KmlUtils {

    // 静态字段，用于存储航点列表
    private static List<Waypoints> waypointsList;

    // 设置航点列表的方法
    public static void setWaypointsList(List<Waypoints> waypointsList) {
        KmlUtils.waypointsList = waypointsList;
    }


    /**
     * 生成KMZ文件
     * @param taskHistory 任务历史记录
     * @return 生成的KMZ文件
     */
    public static File generateKmz(TaskHistory taskHistory) throws IOException {
        String kmlContent = generateKml(taskHistory,waypointsList);
        String tempDir = System.getProperty("java.io.tmpdir");
        File kmlFile = new File(tempDir, "doc.kml");
        File kmzFile = new File(tempDir, taskHistory.getRecordId() + ".kmz");

        try {
            FileUtils.writeStringToFile(kmlFile, kmlContent, StandardCharsets.UTF_8);

            try (FileOutputStream fos = new FileOutputStream(kmzFile);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {

                ZipEntry zipEntry = new ZipEntry("doc.kml");

                zos.putNextEntry(zipEntry);

                byte[] bytes = FileUtils.readFileToByteArray(kmlFile);

                zos.write(bytes);
                zos.closeEntry();
            }

            return kmzFile;
        } finally {
            // 5. 清理临时KML文件
            if (kmlFile.exists()) {
                kmlFile.delete();
            }
        }
    }

    /**
     * 生成KML内容
     * @param taskHistory 任务历史记录
     * @return KML字符串
     */
    private static String generateKml(TaskHistory taskHistory,List<Waypoints> waypointsList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        StringBuilder kml = new StringBuilder();
        kml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        kml.append("<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n");
        kml.append("  <Document>\n");

        // 添加任务基本信息
        kml.append("    <name>").append(taskHistory.getTaskName()).append("</name>\n");
        kml.append("    <description><![CDATA[\n");
        kml.append("      任务ID: ").append(taskHistory.getTaskId()).append("\n");
        kml.append("      执行时间: ").append(sdf.format(taskHistory.getExecTime())).append("\n");
        kml.append("      执行状态: ").append((taskHistory.getStatus())).append("\n");
        kml.append("      飞手: ").append(taskHistory.getPilotName()).append("\n");
        kml.append("      所属部门: ").append(taskHistory.getDeptName()).append("\n");
        kml.append("      设备名称: ").append(taskHistory.getDroneName()).append("\n");
        kml.append("      机场名称: ").append(taskHistory.getDockName()).append("\n");
        kml.append("      飞行地点: ").append(taskHistory.getFlightLocation()).append("\n");
        kml.append("      飞行信息: ").append(taskHistory.getFlightInfo()).append("\n");
        kml.append("    ]]></description>\n");

        // 添加样式
        kml.append("    <Style id=\"taskStyle\">\n");
        kml.append("      <IconStyle>\n");
        kml.append("        <Icon>\n");
        kml.append("          <href>http://maps.google.com/mapfiles/kml/paddle/red-circle.png</href>\n");
        kml.append("        </Icon>\n");
        kml.append("      </IconStyle>\n");
        kml.append("      <LabelStyle>\n");
        kml.append("        <scale>1.0</scale>\n");
        kml.append("      </LabelStyle>\n");
        kml.append("    </Style>\n");

        // 添加任务点位标记
        kml.append("    <Placemark>\n");
        kml.append("      <name>").append(taskHistory.getTaskName()).append("</name>\n");
        kml.append("      <styleUrl>#taskStyle</styleUrl>\n");
        kml.append("      <description><![CDATA[\n");
        kml.append("        设备: ").append(taskHistory.getDroneName()).append("\n");
        kml.append("        地点: ").append(taskHistory.getFlightLocation()).append("\n");
        kml.append("        信息: ").append(taskHistory.getFlightInfo()).append("\n");
        kml.append("      ]]></description>\n");

        // 添加航点列表
        if(waypointsList != null && !waypointsList.isEmpty()) {
            kml.append("      <Point>\n");
            kml.append("      <coordinates>");
            for (Waypoints waypoint : waypointsList) {
                kml.append(waypoint.getWpLongitude()).append(", ").append(waypoint.getWpLatitude()).append(", ").append(waypoint.getWpAltitude()).append("\n");
            }
            kml.append("      </coordinates>\n");
            kml.append("      </Point>\n");
            kml.append("    </Placemark>\n");

        }
        else{
            // 注意：这里需要添加实际的经纬度坐标，目前用示例坐标
            kml.append("      <Point>\n");
            kml.append("        <coordinates>116.404,39.915,0</coordinates>\n");
            kml.append("      </Point>\n");
            kml.append("    </Placemark>\n");
        }


        kml.append("  </Document>\n");
        kml.append("</kml>");

        return kml.toString();
    }
}